//
//  String+APP.swift
//  iPhone
//
//  Created by Toj on 5/31/22.
//

import Foundation

extension String {
    
    static func signatureOrder(userID: String, nonce: String, timestamp: Int, encrypted: String) -> Self {
        
        let point = timestamp % 4
        if point == 0 {
            return encrypted + userID + nonce + "\(timestamp)"
        }
        
        if point == 1 {
            return userID + encrypted + nonce + "\(timestamp)"
        }
        
        if point == 2 {
            return userID + nonce + encrypted + "\(timestamp)"
        }
        
        return userID + nonce + "\(timestamp)" + encrypted
    }
    
    func cm_hmacSHA256(key: String) -> String {
        return cm_hmac(algorithm: .SHA256, key: key)
    }
    
    /* 对电话号混淆 */
    func st_confusePhone(replace confuse: String) -> String {
        let account = self
        guard !account.isEmpty else { return account }
        
        var accountText = account
        let accountCount = account.count
        if accountCount > 6 {
            let startRange = account.index(account.startIndex, offsetBy: 3)
            let endRange = account.index(account.startIndex, offsetBy: (accountCount-3))
            let range = startRange..<endRange
            accountText.replaceSubrange(range, with: confuse)
        }
        return accountText
    }
    
    /* 对Email混淆 */
    func st_confuseEmail(replace confuse: String) -> String {
        var emailText = self
        
        let components = emailText.components(separatedBy: "@")
        let domain = components.last ?? ""
        let emailSuffix = "@" + domain
        var uid = components.first ?? ""
        
        guard !uid.isEmpty else { return emailText }
        
        let uidLength = uid.count
        if uidLength < 6 { // [1,5]
            let suffixCount = uidLength < 5 ? 1 : 2
            let length = uidLength - suffixCount
            emailText = String(uid.prefix(length)) + confuse + emailSuffix
            print("-->UTests: uidString prefix: \(emailText) ")
            return emailText
        }
        
        // [6,~]
        let startRange = uid.index(uid.startIndex, offsetBy: 3)
        let endRange = uid.index(uid.startIndex, offsetBy: uid.count-2)
        let range = startRange..<endRange
        uid.replaceSubrange(range, with: confuse)
        emailText = uid + emailSuffix
        print("-->UTests: uidString range: \(emailText) ")
        return emailText
    }
}

public class FunctionManager: NSObject {
    static let manager = FunctionManager()
    
    // 签名key
    private var _signatureKey: String?
    public var signatureKeyString: String {
        // 后期走服务端
        guard _signatureKey == nil else {
            // print("_signatureKey: " + #function)
            return _signatureKey ?? ""
        }
        // print("FunctionManager: " + #function)
        let keyString = ""
        _signatureKey = keyString
        return keyString
    }
}
